<template>
  <div class="job-filter-container">
    <h2>工作筛选</h2>
    
    <!-- 筛选条件区域 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="100px" size="default">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工作类型">
              <el-select v-model="filterForm.jobType" placeholder="选择工作类型" clearable style="width: 100%">
                <el-option label="普工" value="普工" />
                <el-option label="装卸工" value="装卸工" />
                <el-option label="搬运工" value="搬运工" />
                <el-option label="仓管员" value="仓管员" />
                <el-option label="快递员" value="快递员" />
                <el-option label="服务员" value="服务员" />
                <el-option label="销售员" value="销售员" />
                <el-option label="保洁" value="保洁" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作地点">
              <el-select v-model="filterForm.location" placeholder="选择工作地点" clearable filterable style="width: 100%">
                <el-option v-for="item in locationOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作时间">
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="最低报酬">
              <el-input-number v-model="filterForm.minSalary" :min="0" :step="100" :precision="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关键词">
              <el-input v-model="filterForm.keyword" placeholder="搜索任务标题或内容" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8" class="filter-actions">
            <el-button type="primary" @click="applyFilter">
              <el-icon><Search /></el-icon>筛选
            </el-button>
            <el-button @click="resetFilter">重置</el-button>
            <el-button type="success" @click="loadRecommendedTasks">推荐工作</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    
    <!-- 筛选结果展示 -->
    <div class="task-list">
      <div class="task-list-header">
        <h3>
          {{ isRecommended ? '推荐工作' : '筛选结果' }} 
          <span class="task-count" v-if="filteredTasks.length > 0">(共{{ filteredTasks.length }}个)</span>
        </h3>
        <div class="task-sort">
          <el-radio-group v-model="sortBy" size="small" @change="sortTasks">
            <el-radio-button label="time">按发布时间</el-radio-button>
            <el-radio-button label="salary">按报酬</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="pagedTasks"
        style="width: 100%"
        @row-click="handleRowClick"
        :empty-text="loading ? '加载中...' : '没有符合条件的工作'"
      >
        <el-table-column prop="title" label="任务标题" min-width="150">
          <template #default="scope">
            <div class="task-title">{{ scope.row.title }}</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="companyName" label="发布企业" min-width="120" />
        
        <el-table-column prop="location" label="工作地点" min-width="120" />
        
        <el-table-column label="工作时间" min-width="180">
          <template #default="scope">
            <span>{{ formatDate(scope.row.startTime) }} 至 {{ formatDate(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="salary" label="报酬" min-width="100">
          <template #default="scope">
            <span class="salary">{{ scope.row.salary }} 元</span>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="匹配度" width="120" v-if="isRecommended">
          <template #default="scope">
            <el-progress :percentage="scope.row.matchRate || 100" :color="getMatchColor(scope.row.matchRate)" />
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click.stop="viewTaskDetail(scope.row.id)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="empty-block" v-if="filteredTasks.length === 0 && !loading">
        <el-empty :description="isRecommended ? '暂无推荐工作' : '没有符合条件的工作'" />
        <div class="empty-actions" v-if="isRecommended">
          <el-button type="primary" @click="resetFilter">查看全部工作</el-button>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination-container" v-if="filteredTasks.length > 0">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredTasks.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getTaskList } from '@/api/task'
import { getWorkerInfo } from '@/api/worker'
import { formatDate } from '@/utils/format'

const router = useRouter()
const loading = ref(false)
const allTasks = ref([])
const filteredTasks = ref([])
const isRecommended = ref(true)
const sortBy = ref('time')
const workerInfo = ref(null)
const locationOptions = ref([
  '北京市', '上海市', '广州市', '深圳市', '杭州市', 
  '南京市', '武汉市', '成都市', '重庆市', '西安市'
])

// 筛选条件
const filterForm = ref({
  jobType: '',
  location: '',
  dateRange: null,
  minSalary: null,
  keyword: ''
})

// 分页设置
const pagination = ref({
  currentPage: 1,
  pageSize: 10
})

// 计算分页后的任务列表
const pagedTasks = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredTasks.value.slice(start, end)
})

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    const response = await getTaskList()
    if (response.success) {
      allTasks.value = response.data || []
      console.log('加载任务列表成功:', allTasks.value.length)
      if (isRecommended.value) {
        loadRecommendedTasks() // 自动加载推荐任务
      } else {
        applyFilter() // 应用筛选条件
      }
    } else {
      ElMessage.error(response.message || '获取任务列表失败')
      filteredTasks.value = []
    }
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error(error.message || '获取任务列表失败')
    filteredTasks.value = []
  } finally {
    loading.value = false
  }
}

// 加载零工信息
const loadWorkerInfo = async () => {
  try {
    const response = await getWorkerInfo()
    if (response.data) {
      workerInfo.value = response.data
      console.log('加载零工信息成功:', workerInfo.value)
      
      // 根据用户信息预设筛选条件
      if (workerInfo.value.skillType) {
        filterForm.value.jobType = workerInfo.value.skillType
      }
      
      // 加载推荐任务
      loadRecommendedTasks()
    }
  } catch (error) {
    console.error('加载零工信息失败:', error)
    // 如果获取不到用户信息，仍然加载所有任务
    loadTasks()
  }
}

// 加载推荐任务
const loadRecommendedTasks = () => {
  isRecommended.value = true
  loading.value = true
  
  try {
    // 根据用户偏好筛选任务
    const recommendedTasks = allTasks.value.filter(task => {
      // 默认匹配率为0
      task.matchRate = 0
      
      // 如果有工种匹配，增加匹配率
      if (workerInfo.value && workerInfo.value.skillType && 
          task.title && task.title.includes(workerInfo.value.skillType)) {
        task.matchRate += 50
      }
      
      // 如果有内容匹配，增加匹配率
      if (workerInfo.value && workerInfo.value.skillType && 
          task.content && task.content.includes(workerInfo.value.skillType)) {
        task.matchRate += 30
      }
      
      // 返回匹配率大于0或任务状态为已发布的任务
      return task.matchRate > 0 || task.status === 'published'
    })
    
    // 根据匹配率排序
    recommendedTasks.sort((a, b) => (b.matchRate || 0) - (a.matchRate || 0))
    
    filteredTasks.value = recommendedTasks
    pagination.value.currentPage = 1
  } catch (error) {
    console.error('推荐任务失败:', error)
    filteredTasks.value = []
  } finally {
    loading.value = false
  }
}

// 应用筛选条件
const applyFilter = () => {
  isRecommended.value = false
  loading.value = true
  
  try {
    const filtered = allTasks.value.filter(task => {
      // 工作类型筛选
      if (filterForm.value.jobType && 
          (!task.title || !task.title.includes(filterForm.value.jobType)) && 
          (!task.content || !task.content.includes(filterForm.value.jobType))) {
        return false
      }
      
      // 工作地点筛选
      if (filterForm.value.location && 
          (!task.location || !task.location.includes(filterForm.value.location))) {
        return false
      }
      
      // 日期范围筛选
      if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
        const startDate = new Date(filterForm.value.dateRange[0])
        const endDate = new Date(filterForm.value.dateRange[1])
        const taskStart = new Date(task.startTime)
        const taskEnd = new Date(task.endTime)
        
        if (taskStart < startDate || taskEnd > endDate) {
          return false
        }
      }
      
      // 最低报酬筛选
      if (filterForm.value.minSalary && task.salary < filterForm.value.minSalary) {
        return false
      }
      
      // 关键词筛选
      if (filterForm.value.keyword) {
        const keyword = filterForm.value.keyword.toLowerCase()
        const titleMatch = task.title && task.title.toLowerCase().includes(keyword)
        const contentMatch = task.content && task.content.toLowerCase().includes(keyword)
        
        if (!titleMatch && !contentMatch) {
          return false
        }
      }
      
      return true
    })
    
    filteredTasks.value = filtered
    pagination.value.currentPage = 1
    
    // 如果没有筛选结果，显示提示
    if (filtered.length === 0) {
      ElMessage.info('没有符合条件的工作')
    }
  } catch (error) {
    console.error('筛选任务失败:', error)
    filteredTasks.value = []
  } finally {
    loading.value = false
  }
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.value = {
    jobType: '',
    location: '',
    dateRange: null,
    minSalary: null,
    keyword: ''
  }
  
  isRecommended.value = false
  sortBy.value = 'time'
  
  // 显示所有任务
  filteredTasks.value = [...allTasks.value]
  sortTasks()
  pagination.value.currentPage = 1
}

// 排序任务
const sortTasks = () => {
  if (sortBy.value === 'time') {
    filteredTasks.value.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  } else if (sortBy.value === 'salary') {
    filteredTasks.value.sort((a, b) => b.salary - a.salary)
  }
}

// 获取任务状态样式
const getStatusType = (status) => {
  switch (status) {
    case 'published': return 'primary'
    case 'assigned': return 'success'
    case 'completed': return 'info'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取任务状态文字
const getStatusText = (status) => {
  switch (status) {
    case 'published': return '已发布'
    case 'assigned': return '已分配'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 获取匹配度颜色
const getMatchColor = (matchRate) => {
  if (matchRate >= 80) return '#67C23A'  // 高匹配 - 绿色
  if (matchRate >= 50) return '#E6A23C'  // 中匹配 - 黄色
  return '#909399'  // 低匹配 - 灰色
}

// 点击行查看详情
const handleRowClick = (row) => {
  viewTaskDetail(row.id)
}

// 查看任务详情
const viewTaskDetail = (taskId) => {
  router.push(`/task/${taskId}`)
}

// 分页处理函数
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
}

// 组件挂载时加载数据
onMounted(() => {
  // 首先加载零工信息，然后加载任务
  loadWorkerInfo()
  loadTasks()
})
</script>

<style scoped>
.job-filter-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.task-list {
  margin-top: 30px;
}

.task-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-count {
  font-size: 14px;
  color: #909399;
  margin-left: 10px;
}

.task-title {
  font-weight: bold;
}

.salary {
  color: #F56C6C;
  font-weight: bold;
}

.empty-block {
  margin: 30px 0;
  text-align: center;
}

.empty-actions {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 